package controller
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.*;
	import flash.events.*;	
	import mx.utils.*;	
	import mx.controls.Alert;
	import controller.events.*;
	import mx.core.FlexGlobals;
	public class SocketManager extends EventDispatcher
	{
		// static instance 
		protected static var instance:SocketManager = null;
		//XmlSocket
		static private var base64decode:Base64Decoder;
		static private var base64encode:Base64Encoder;
		static private var xmlSocket:XMLSocket;
		public function SocketManager(target:IEventDispatcher=null)
		{
			super(target);
			if ( instance != null )
				throw new Error( "Only one Singleton instance should be instantiated" ); 
			initSocket();
		}
		public function init():void{
			
		}
		private function initSocket():void{
			base64decode=new Base64Decoder();
			base64encode=new Base64Encoder();			
			xmlSocket = new XMLSocket();   
			xmlSocket.addEventListener(Event.CONNECT,connectionFun); 
			xmlSocket.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			xmlSocket.addEventListener(Event.CLOSE,closeFun);  
			xmlSocket.addEventListener(DataEvent.DATA,receiveMsg);  
			xmlSocket.addEventListener(ProgressEvent.PROGRESS, progressHandler);  
			xmlSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); 
			xmlSocket.connect("10.10.8.48",2009);  //192.168.56.1
			
		}
		/** 
		 * 断开连接 
		 */  
		public function disconnect():void{            
			if(xmlSocket.connected){  
				xmlSocket.close();  
				xmlSocket.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);  
				xmlSocket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);  
				xmlSocket.removeEventListener(Event.CONNECT,connectionFun);  
				xmlSocket.removeEventListener(DataEvent.DATA,receiveMsg);  
				xmlSocket.removeEventListener(Event.CLOSE,closeFun);  
				dispatchEvent(new Event(Event.CLOSE));  
			}  
			trace("disconnect success");
		}  
		
		private function ioErrorHandler(event:IOErrorEvent):void {			
			Alert.show("ioErrorHandler: " + event);
		}			
		
		private function connectionFun(event:Event):void{  
			//				Alert.show("n");  
			trace("已经成功连接到服务器");
		}  
		private function closeFun(event:Event):void{  
			Alert.show("已经断开服务器\n");  
			FlexGlobals.topLevelApplication.currentState = "MainMenu";
			ControllerManager.Instance.state=0;
		}  
		private function receiveMsg(event:DataEvent):void{  
			// 恢复请求许可				 
			base64decode.decode(event.data);
			var msg:String=base64decode.toByteArray().toString();  	
			trace("接到服务器消息："+msg);
			 var results:Array=msg.split("~",4);
			 dispatchEvent(new SocketEvent(results[2], results));
			 trace("派发消息成功："+results[2]);
			 /*switch(results[0])
			{
			case "1":
			playerInMessageHandler(results);
			break;
			case "2":
			break;
			case "3":
			break;
			}*/
			//0~0~SERVER_IDLE_TEST~null				
			
		}	
		private function progressHandler(event:ProgressEvent):void {
			trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}		
		public function send(msg:String):void
		{
			//trace("向");
			if(xmlSocket!=null&&xmlSocket.connected)
			{
				base64encode.encodeUTFBytes(msg);
				msg=base64encode.toString();
				trace(msg);
				xmlSocket.send(msg);  
			}
			else
			{
			trace("服务器断开，发送消息失败！");
			}
		}
		static public function get Instance():SocketManager
		{
			if ( instance == null )
				instance = new SocketManager();
			return instance;
		}
	}
}